package org.niit.flume;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TypeInterceptor implements Interceptor {
     //声明一个存放事件的集合  将添加Header的事件放到这个集合中
    private List<Event> addHeaderEvents;

    //初始化的方法
    @Override
    public void initialize() {
        addHeaderEvents = new ArrayList<>();
    }
    //拦截单个事件的方法
    @Override
    public Event intercept(Event event) {
        //1.获取事件的Header
        Map<String, String> headers = event.getHeaders();
        //2.获取事件的Body
        String body = new String(event.getBody());
        //3.判断body的信息是否包含指定的内容，根据指定的内容去设置header
        if(body.contains("MYFLUME")){
            headers.put("type","first");
        }else{
            headers.put("type","second");
        }
        return event;
    }
    //拦截多个事件的方法
    @Override
    public List<Event> intercept(List<Event> list) {
        for (Event event:list){
            Event newEvent = intercept(event);
            addHeaderEvents.add(newEvent);
        }
        return addHeaderEvents;
    }
    //关闭的方法
    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder{

        @Override
        public Interceptor build() {
            return new TypeInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
